package com.fingard.dsp.bank.directbank.fubon01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.text.DecimalFormat;
import java.util.Date;

public class FUBON01Transaction extends FUBON01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7515.reqHeader);
        //写返回ATS的统一头部信息
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();
        try {
            int page = 1;
            boolean more = false;
            String curtype = "";
            String lastPageTime = "";
            String lastPageBalance = "";
            String lastPageBookBalance = "";
            String lastPageAvaibleBalance = "";
            do {
                //全局流水
                String transSeqId = p_req7515.reqHeader.transSeqID;
                transSeqId = bankFront.corpNo + "01" + "301010" + Format.Date8Format.format(new Date()) + "00" + transSeqId.substring(transSeqId.length() - 8, transSeqId.length());

                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                FUBON01Header fubon01Header = new FUBON01Header();
                fubon01Header.ServiceCode = "06002010002";//服务唯一标识，由EAI提供
                fubon01Header.ServiceScene = "01";//服务场景
                fubon01Header.InitiatorId = "203010";//发起方系统编号
                fubon01Header.ServiceId = "301010";//服务系统编号
                fubon01Header.TranDate = Format.Date8Format.format(new Date());//前台交易日期 YYYYMMDD
                fubon01Header.TranTime = Format.Time6Format.format(new Date());//前台交易时间 hhmmss
                fubon01Header.OrgConSeqNo = transSeqId;//发起方流水号 全局流水号
                fubon01Header.ConsumerSeqNo = transSeqId;//消费方流水号 调用方产生流水号
                fubon01Header.FileFlag = "0";//文件标识 1-有文件，0-无文件
                writeCommonHeader(xmlWriter, fubon01Header);

                xmlWriter.writeStartElement("Body");
                xmlWriter.writeElementString("AccountType", "CA");//帐户类型
                xmlWriter.writeElementString("Acct", p_req7515.actNum);
                xmlWriter.writeElementString("Ccy", convertCurToBank(p_req7515.actCur));
                xmlWriter.writeElementString("Mark", "");//????钞汇标志
                xmlWriter.writeElementString("TransDate", Format.Date8Format.format(new Date()));//银行帐务日
                xmlWriter.writeElementString("MaxReNum", "50");//最大的数据笔数
                xmlWriter.writeElementString("PageNo", String.format("%02d", page));//查询页号
                xmlWriter.writeElementString("LastPageTime", lastPageTime);//上页最末行交易时间
                xmlWriter.writeElementString("LastPageBalance", lastPageBalance);//上页最末行交易后余额
                xmlWriter.writeElementString("LastPageBookBalance", lastPageBookBalance);//上页最末行帐面余额
                xmlWriter.writeElementString("LastPageAvaibleBalance", lastPageAvaibleBalance);//上页最末行可用余额
                xmlWriter.writeEndDocument();

                //gxp通讯报文头
                fubon01Header.glbTrSeq = transSeqId;
                fubon01Header.recvId = "CORE";//服务方ID
                String gxpHeader = writeGxpHeader(fubon01Header, xmlWriter.toXmlString());

                String[] tmpRetBkStr = sendToBankQry(gxpHeader, gxpHeader + xmlWriter.toXmlString());
//                String[] tmpRetBkStr = {"", "<service>\n" +
//                        "    <GapsAppHead>\n" +
//                        "        <RespCode>000000</RespCode>\n" +
//                        "        <RespMsg>交易成功</RespMsg>\n" +
//                        "        <OrgConSeqNo>20200302155258297</OrgConSeqNo>\n" +
//                        "        <ConsumerSeqNo>446283</ConsumerSeqNo>\n" +
//                        "        <FileFlag>0</FileFlag>\n" +
//                        "        <TranDate>20200302</TranDate>\n" +
//                        "        <TranTime>155259</TranTime>\n" +
//                        "        <TellerNo>0000000000</TellerNo>\n" +
//                        "        <BranchId>0000000000</BranchId>\n" +
//                        "        <TellerPassword></TellerPassword>\n" +
//                        "        <TellerLevel></TellerLevel>\n" +
//                        "        <TellerType></TellerType>\n" +
//                        "        <ApprFlag></ApprFlag>\n" +
//                        "        <ApprTellerArray>\n" +
//                        "            <ApprTellerNo></ApprTellerNo>\n" +
//                        "            <ApprBranchId></ApprBranchId>\n" +
//                        "            <ApprTellerLevel></ApprTellerLevel>\n" +
//                        "            <ApprTellerType></ApprTellerType>\n" +
//                        "        </ApprTellerArray>\n" +
//                        "        <AuthTellerInfo>\n" +
//                        "            <AuthTellerNo></AuthTellerNo>\n" +
//                        "            <AuthBranchId></AuthBranchId>\n" +
//                        "            <AuthTellerPassword></AuthTellerPassword>\n" +
//                        "            <AuthTellerLevel></AuthTellerLevel>\n" +
//                        "            <AuthTellerType></AuthTellerType>\n" +
//                        "        </AuthTellerInfo>\n" +
//                        "        <AuthFlag></AuthFlag>\n" +
//                        "        <BckFld1></BckFld1>\n" +
//                        "        <BckFld2></BckFld2>\n" +
//                        "        <BckFld3></BckFld3>\n" +
//                        "        <BckFld4></BckFld4>\n" +
//                        "        <BckFld5></BckFld5>\n" +
//                        "    </GapsAppHead>\n" +
//                        "    <Body>\n" +
//                        "        <AccountType>CA</AccountType>\n" +
//                        "        <Acct>10000020100003970</Acct>\n" +
//                        "        <Ccy>RMB</Ccy>\n" +
//                        "        <Mark></Mark>\n" +
//                        "        <Balance>90000000</Balance>\n" +
//                        "        <BookBalance>90000000</BookBalance>\n" +
//                        "        <AvaibleBalance>90000000</AvaibleBalance>\n" +
//                        "        <EOF>E</EOF>\n" +
//                        "        <PageNo>1</PageNo>\n" +
//                        "        <ReNum>2</ReNum>\n" +
//                        "        <FTZ></FTZ>\n" +
//                        "        <AcctTransDetlList>\n" +
//                        "            <AcctTransDetl>\n" +
//                        "                <CR_DR>DR</CR_DR>\n" +
//                        "                <TransAmt>100+</TransAmt>\n" +
//                        "                <TransDate>20200310</TransDate>\n" +
//                        "                <TransTime>080000</TransTime>\n" +
//                        "                <CoreNo>1234</CoreNo>\n" +
//                        "                <IntDate>20200310</IntDate>\n" +
//                        "                <InputDay>20200310</InputDay>\n" +
//                        "                <CorrectFlag></CorrectFlag>\n" +
//                        "                <TransType>61</TransType>\n" +
//                        "                <TransTypeDesc>RWERWETWFW</TransTypeDesc>\n" +
//                        "                <TransRemark></TransRemark>\n" +
//                        "                <TransRemark2>备注1</TransRemark2>\n" +
//                        "            </AcctTransDetl>\n" +
//                        "            <AcctTransDetl>\n" +
//                        "                <CR_DR>CR</CR_DR>\n" +
//                        "                <TransAmt>10011+</TransAmt>\n" +
//                        "                <TransDate>20200310</TransDate>\n" +
//                        "                <TransTime>080000</TransTime>\n" +
//                        "                <CoreNo>1244</CoreNo>\n" +
//                        "                <IntDate>20200310</IntDate>\n" +
//                        "                <InputDay>20200310</InputDay>\n" +
//                        "                <CorrectFlag></CorrectFlag>\n" +
//                        "                <TransType>61</TransType>\n" +
//                        "                <TransTypeDesc>RWERWETWFW</TransTypeDesc>\n" +
//                        "                <TransRemark></TransRemark>\n" +
//                        "                <TransRemark2>备注1</TransRemark2>\n" +
//                        "            </AcctTransDetl>\n" +
//                        "        </AcctTransDetlList>\n" +
//                        "    </Body>\n" +
//                        "</service>"};
                if (tmpRetBkStr[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String returnCode = tmpBkReader.getFirstText("/service/GapsAppHead/RespCode");
                        String returnMsg = tmpBkReader.getFirstText("/service/GapsAppHead/RespMsg");
                        if (returnCode != null && "000000".equals(returnCode)) {
                            String hasNextPage = tmpBkReader.getFirstText("/service/Body/EOF");//是否还有下一页 ，E-最后一页，N-还有下一页
                            if (hasNextPage.equals("E")) {//E - 最后一页
                                more = false;
                            } else {
                                //还有下一页
                                more = true;
                                curtype = tmpBkReader.getFirstText("/service/Body/Ccy");
                                lastPageTime = tmpBkReader.getFirstText("/service/Body/TransTime");
                                lastPageBalance = tmpBkReader.getFirstText("/service/Body/Balance");
                                lastPageBookBalance = tmpBkReader.getFirstText("/service/Body/BookBalance");
                                lastPageAvaibleBalance = tmpBkReader.getFirstText("/service/Body/AvaibleBalance");
                            }
                            while (tmpBkReader.read("/service/Body/AcctTransDetlList/AcctTransDetl")) {
                                RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                XElement tmpRecord = tmpBkReader.readedXElement;
                                tmpRetDetail.actArea = p_req7515.actArea;//银行地区区域码
                                tmpRetDetail.actNum = p_req7515.actNum;//银行账号
                                //交易日期
                                String tranDate = tmpRecord.getSingleText("TransDate");
                                tmpRetDetail.tranDate = tranDate.substring(0, 4) + "-" + tranDate.substring(4, 6) + "-" + tranDate.substring(6, 8);
                                //交易时间
                                String tranTime = tmpRecord.getSingleText("TransTime");
                                tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + tranTime.substring(0, 2) + ":" + tranTime.substring(2, 4) + ":" + tranTime.substring(4, 6);
                                //起息日期
                                String valueDate = tmpRecord.getSingleText("IntDate");
                                tmpRetDetail.valueDate = valueDate.substring(0, 4) + "-" + valueDate.substring(4, 6) + "-" + valueDate.substring(6, 8);

                                DecimalFormat df = new DecimalFormat();
                                String style = "0.00";
                                //交易金额，最后一位是符号位，无小数
                                String tranAmt = tmpRecord.getSingleText("TransAmt");
                                tranAmt = tranAmt.substring(0, tranAmt.length() - 1);
                                df.applyPattern(style);
                                tmpRetDetail.tranAmt = df.format(Double.parseDouble(tranAmt) / 100.00);

//                                //账号余额，最后一位是符号位，无小数
//                                String accBal = tmpBkReader.getFirstText("Balance");
//                                accBal = accBal.substring(0, accBal.length() - 1);
//                                df.applyPattern(style);
//                                tmpRetDetail.accBal = df.format(Double.parseDouble(accBal) / 100.00);

                                //借贷标志 ‘DR’- 借方发生 ‘CR’ – 贷方发生
                                String cdFlag = tmpRecord.getSingleText("CR_DR");
                                if ("CR".equals(cdFlag)) {
                                    tmpRetDetail.cdFlag = "2";//借贷标志
                                } else if ("DR".equals(cdFlag)) {
                                    tmpRetDetail.cdFlag = "1";//借贷标志
                                }

                                tmpRetDetail.usage = getBankConfig().getMapValueByKey("transType", tmpRecord.getSingleText("TransType"));//用途

                                tmpRetDetail.comment = StringHelper.joinNotEmpty(";", tmpRecord.getSingleText("TransRemark"), tmpRecord.getSingleText("TransRemark2"));//备注
                                tmpRetDetail.cur = p_req7515.actCur;//币种
                                retAts.writeRetDetail(tmpRetDetail);
                            }

                        } else {
                            String tmpreturnMsg = StringHelper.isNullOrEmpty(getBankConfig().getMapValueByKey("fail_code", returnCode)) ? returnMsg : getBankConfig().getMapValueByKey("fail_code", returnCode);
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpreturnMsg;
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpRetBkStr[1];
                    break;
                }
                page++;//请求页数+1
            } while (more);
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
            retAts.writeEnd();
            return retAts;
        }
        if ("-1".equals(tmpRespCode)) {
            if (tmpRespInfo.contains("RECORD DOES NOT EXIST4")) {
                retAts.writeRespCode("0");
                retAts.writeRespInfo("交易为空!");
            } else {
                retAts.writeRespCode(tmpRespCode);
                retAts.writeRespInfo(tmpRespInfo);
            }
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空!");
        }
        retAts.writeEndWithoutInsertDB();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        return null;
    }


}
